package com.tedu.firstspringboot.controller;

import com.tedu.firstspringboot.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

@Controller
public class UserController {
    private static File userDir;
    static {
        userDir = new File("./users");
        if(!userDir.exists()){
            userDir.mkdirs();
        }
    }

    //@
    @RequestMapping("/regUser")
    public void reg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String nickname = request.getParameter("nickname");
        String ageStr = request.getParameter("age");

        int age = Integer.parseInt(ageStr);

        User user = new User(username,password,nickname,age);
        File file = new File(userDir,username + ".obj");

        if(username == null || username.trim().isEmpty() ||
           password == null || password.trim().isEmpty() ||
           nickname == null || nickname.trim().isEmpty() ||
           ageStr == null || ageStr.trim().isEmpty() ||
           !ageStr.matches("[0-9]+")) {
            try {
                response.sendRedirect("/reg_info_error.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
        System.out.println("用户名:" + username + " 密码:" + password + " 昵称:" + nickname + " 年龄:" + ageStr);



        try (
                FileOutputStream fos = new FileOutputStream(file);
                ObjectOutputStream oos = new ObjectOutputStream(fos);
        ){
            oos.writeObject(user);

            response.sendRedirect("/reg_success.html");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void log(HttpServletRequest request, HttpServletResponse response){}
}
